import Axios from 'axios';
import { Toast, Dialog } from 'vant';
import { i18n } from '@/locales';
export default class AppUpdate {
  constructor() {
    this.$t = i18n.global.t;
  }

  init({ url = '', ttid = '', mode = '' }) {
    if (!url && !ttid && !mode) {
      return new Error('参数不能为空');
    }
    this.url = url;
    this.ttid = ttid;
    this.mode = mode;
  }

  checkUpdate() {
    return new Promise((resolve, reject) => {
      this.getAppData().then(res => {
        const result = res.data;
        let version = null;

        window.plus.runtime.getProperty(window.plus.runtime.appid, data => {
          version = data.version;

          if (this.mode === result.mode) {
            if (data.forceUpdate || (version !== result.version && this.ttid === result.ttid)) {
              this.update(result.url);
              resolve();
            } else {
              reject(new Error('暂无更新'));
            }
          } else {
            this.update(result.url);
            resolve();
          }

          if (data.cleanStorage) {
            window.localStorage.clear();
            window.sessionStorage.claer();
          }
        });
      });
    });
  }

  async update(url) {
    const path = await this.download(url).finally(() => {
      Toast.clear();
    });

    await this.install(path)
      .then(() => {
        Dialog.alert({
          message: this.$t('installComplete'),
        }).then(() => {
          window.plus.runtime.restart();
        });
      })
      .finally(() => {
        Toast.clear();
      });
  }

  async getAppData() {
    return Axios.get(`${this.url}?_=${new Date().getTime()}`).then(res => {
      return res;
    });
  }

  download(url) {
    Toast.loading({
      forbidClick: true,
      message: this.$t('appUpdate'),
      duration: 0,
    });

    return new Promise((resolve, reject) => {
      window.plus.downloader
        .createDownload(url, { filename: '_downloads/update/' }, (d, status) => {
          if (status === 200) {
            resolve(d.filename);
          } else {
            Dialog.alert({
              message: this.$t('downloadFail'),
            });
            reject(new Error(this.$t('downloadFail')));
          }
        })
        .start();
    });
  }

  install(path) {
    Toast.loading({
      forbidClick: true,
      message: this.$t('appInstall'),
      duration: 0,
    });

    return new Promise((resolve, reject) => {
      window.plus.runtime.install(
        path,
        { force: true },
        () => {
          resolve();
        },
        error => {
          Dialog.alert({
            title: this.$t('hint'),
            message: `${this.$t('installFail')}[${error.code}]：${error.message}`,
          });
          reject(new Error(this.$t('installFail')));
        },
      );
    });
  }
}
